//need express and ejs
var express = require('express'),
    http = require('http'),
    sinaOAuth = require('./lib/sinaOAuth'),
    sys = require('sys'),
    app = express.createServer(),
    registerService = require('./services/registerService'),
    controller = require( "./controller.js" );

(function initController(){
    controller.registerService = registerService;
    controller.on("data", function(data, req, res){
        res.writeHead(200, {
            "Content-Type": "text/plain"
        });
        res.write( JSON.stringify( data ) );
        res.end();
    });

    controller.on("error", function(errorType, req, res){
        res.writeHead(errorType, {
            "Content-Type": "text/plain"
        });
        res.end();
    });
})();

app.use(express.logger({ format: ':method :url :status' }));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'bang590' }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));

app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.error(function(err, req, res){
    console.log("500:" + err + " file:" + req.url)
    res.render('500');
});

app.set('views', __dirname + '/views');
app.register('.html', require('ejs'));
app.set('view engine', 'html');
app.set('view options', {layout: false})


app.get('/', function(req, res){
    res.render('index.html');
});

app.get('/ext', function(req, res){
    res.render('ext_index.html');
});

app.get('/oauth', function(req, res){
    var sinaoauth = new sinaOAuth();
    sinaoauth.oAuth(req, res, function(error, access_key, access_secret, results) {
        //save oauth_access_token
        registerService.upsert({
            oauth_access_token: access_key,
            oauth_access_token_secret: access_secret,
            user_id: results['user_id']
        }, function(){
            res.cookie('uid', results['user_id']);
            res.cookie("access_key", access_key);
            res.cookie("access_secret", access_secret);
            res.render('oauth.html');
        });
    });
});

app.get('/test', function(req, res) {
    var sinaoauth = new sinaOAuth(req.cookies.access_key, req.cookies.access_secret);
    sinaoauth.friends_timeline({}, function(err, data) {
        if (err) return console.log(err);
        res.render('test.html', {statuses: JSON.parse(data)});
    });
});

app.post('/test', function(req, res) {
    var sinaoauth = new sinaOAuth(req.cookies.access_key, req.cookies.access_secret);
    sinaoauth.update({status : req.body.status}, function(err, data){
        if (err) return console.log(err);
        res.redirect('./test');
    });
});

app.get('/favblog/:id', function(req, res){
    if(req.params.id){
        var userCount = 0;
        var statuses = [];
        registerService.getAll(function(err, users){
            userCount = users.length;

            users.forEach(function(user){
                var sinaoauth = new sinaOAuth(user.oauth_access_token, user.oauth_access_token_secret);
                sinaoauth.fav_create({id: req.params.id}, function(err, data){
                    sinaoauth.fav(null, function(err, data){
                        userCount--;
                        var tempStatuses = JSON.parse(data);
                        tempStatuses.forEach(function(item){
                            item.user_id = user.user_id;
                        });
                        statuses = statuses.concat(tempStatuses);
                        if(userCount == 0){
                            res.render('test.html', {statuses: statuses});
                        }
                    });
                });
            });
        });
    }else{
        res.send('no id');
    }
    console.log('todo fav blog');
});

app.get('/user/*', function(req, res){
    console.log('enter user');
    controller.handle(req, res);
});



/* dispatch to java server, replaced in future */

//TODO: use POST method to replace GET
app.get('/proxy/*', function(request, response) {
    var options = {
        host : 'localhost',
        port : 8080,
        method : 'GET'
    };
    var url = request.url.replace('/proxy', '');
    options.path = url;
    var proxyRequest = http.request(options, function(proxyResponse) {
        console.log("Got response: " + proxyResponse.statusCode);
        console.log('HEADERS: ' + JSON.stringify(proxyResponse.headers));
        response.writeHead(200, {
            'content-type' : 'text/plain'
        });
        proxyResponse.on('data', function(chunk) {
            //TODO: we need change addfilter servlet response like below json data
            var result = {
                success : true,
                msg : 'updated'
            };
            response.write(JSON.stringify(result));

            //response.write(chunk);
        });
        proxyResponse.on('end', function(err) {
            response.end();
        });
    });
    proxyRequest.end();
});


app.listen(8888);
sys.puts('server listens on 8888');
